package com.czy.ekp.datasource;


import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.jdbc.DataSourceBuilder;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

public class DynamicDataSourceContextHolder {

    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
    private static DataSource tmpDataSource;
    public static DataSource defaultDataSource;
    public static List<String> dataSourceIds = new ArrayList<>();

    public static void setDataSourceType(String dataSourceType) {
        contextHolder.set(dataSourceType);
    }

    public static void setDataSource(String driverClassName, String url, String username, String password) {
        DataSourceBuilder factory = DataSourceBuilder.create().driverClassName(driverClassName).url(url)
                .username(username).password(password).type(DruidDataSource.class);
        setDataSource(factory.build());
    }
    public static void setDataSource(DataSource dataSource){
        tmpDataSource = dataSource;
        if(tmpDataSource instanceof DruidDataSource){
            DruidDataSource druidDataSource = (DruidDataSource) tmpDataSource;
            druidDataSource.setConnectionErrorRetryAttempts(1);
            druidDataSource.setBreakAfterAcquireFailure(true);
        }
    }

    public static DataSource getDataSource(){
        return tmpDataSource;
    }

    public static String getDataSourceType() {
        return contextHolder.get();
    }

    public static void clearDataSourceType() {
        contextHolder.remove();
    }

    /**
     * 判断指定DataSrouce当前是否存在
     */
    public static boolean containsDataSource(String dataSourceId){
        return dataSourceIds.contains(dataSourceId);
    }
}
